`timescale 1ns / 1ps 
//////////////////////////////////////////////////////////////////////////////////
// Company:
// Engineer:
//
// Create Date: 2022/03/03 09:17:13
// Design Name:
// Module Name: rgb2gray
// Project Name:
// Target Devices:
// Tool Versions:
// Description:
//
// Dependencies:
//
// Revision:
// Revision 0.01 - File Created
// Additional Comments:
//
//////////////////////////////////////////////////////////////////////////////////


module rgb2gray(clk,
                clken,
                rgb,
                resetb,
                ihsync,
                ivsync,
                gray,
                oclken,
                ohsync,
                ovsync

               );
input clk;
input clken;
input resetb;
input [15: 0] rgb;
input ihsync;
input ivsync;
output [ 7: 0] gray;
output oclken;
output ohsync;
output ovsync;
parameter ck2q = 1;
reg ihsync_d0, ihsync_d1, ivsync_d0, ivsync_d1, clken_d0, clken_d1;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			begin
				{ihsync_d1, ihsync_d0} <= #ck2q 0;
				{ivsync_d1, ivsync_d0} <= #ck2q 0;
				{clken_d1 , clken_d0 } <= #ck2q 0;

			end
		else
			begin
				{ihsync_d1, ihsync_d0} <= #ck2q {ihsync_d0, ihsync};
				{ivsync_d1, ivsync_d0} <= #ck2q {ivsync_d0, ivsync};
				{clken_d1 , clken_d0 } <= #ck2q {clken_d0 , clken };
			end
	end
wire [15: 0] red = {rgb[15: 11], rgb[13: 11]};
wire [15: 0] green = {rgb[10: 5 ], rgb[6 : 5 ]};
wire [15: 0] blue = {rgb[4 : 0 ], rgb[2 : 0 ]};
reg [15: 0] gray_r, gray_g, gray_b;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			begin
				gray_r <= #ck2q 0;
				gray_g <= #ck2q 0;
				gray_b <= #ck2q 0;
			end
		else if (clken & ihsync & ivsync)
			begin
				gray_r <= #ck2q (red << 6) + (red << 3) + (red << 2) + red ;
				gray_g <= #ck2q (green << 7) + (green << 4) + (green << 2) + green;
				gray_b <= #ck2q (blue << 4) + (blue << 3) + (blue << 2) + 1'b1 ;
			end
	end

reg [7 : 0] gray;
wire [15: 0] gray_w = gray_r + gray_g + gray_b;
always@(posedge clk or negedge resetb)
	begin
		if (!resetb)
			gray <= #ck2q 0;
		else if (clken_d0 & ihsync_d0 & ivsync_d0)
			gray <= #ck2q gray_w[15: 8];
	end
/*
reg [7:0] gray;
always@(posedge clk or negedge resetb)begin
 if(!resetb)
 gray <= #ck2q 0;
 else if(clken_d0 & ihsync_d0 & ivsync_d0)
 gray <= #ck2q gray + 1'b1;
end
*/
assign oclken = clken_d1;
assign ohsync = ihsync_d1;
assign ovsync = ivsync_d1;
endmodule
